package wsepForum.ui.swing.innerPanels;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import java.util.concurrent.ExecutionException;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.border.MatteBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import wsepForum.common.elements.Section;
import wsepForum.common.elements.SectionHeader;
import wsepForum.common.elements.Topic;
import wsepForum.common.elements.TopicHeader;
import wsepForum.domain.exceptions.SystemFailureException;
import wsepForum.domain.exceptions.UnAuthorizedException;
import wsepForum.network.common.GUIAnswer;
import wsepForum.network.common.GUIAnswer.AnswerType;
import wsepForum.network.common.GUIRequest.RequestType;
import wsepForum.persistance.exceptions.WrongElementIDException;
import wsepForum.ui.swing.SetSwitcher.SetType;
import wsepForum.ui.swing.outerPanels.AOuterPanel;
import wsepForum.ui.swing.workers.ForumWorker;
import javax.swing.JScrollPane;

public class SectionPanel extends AInnerPanel {
	private static final long serialVersionUID = 1L;
	private Section section;
	private boolean editAuth;

	public SectionPanel(Section sec, final boolean editAuth, AOuterPanel oPanel) {
		super(oPanel);
		this.section = sec;
		this.editAuth= editAuth;
		initPanel();
	}

	private void initPanel(){
		setBorder(new MatteBorder(1, 1, 1, 1, new Color(0, 0, 0)));
		setLayout(null);
		setBackground(new Color(230, 230, 250));
		setBounds(20, 93, 716, 364);

		String sectionName = this.section.getHeadLine();

		final JButton btnEnterSection = new JButton("Enter Section");
		final JButton btnEnterTopic = new JButton("Enter Topic");
		final JButton btnAddSection = new JButton("Add SubSection");
		final JButton btnEditSection = new JButton("Edit Section");
		final JButton btnDeleteThisSection = new JButton("Delete Section");
		final JButton btnAddNewTopic = new JButton("Add New Topic");
		final JButton btnBack = new JButton("Back");

		final JLabel panelHeadline = new JLabel(sectionName);
		final JLabel lblSections = new JLabel("Sub-Sections");
		final JLabel lblTopics = new JLabel("Topics");

		Vector<String> sectionVector = new Vector<String>();
		for (SectionHeader sectionHeader : this.section.getAllSectionHeaders()) {
			sectionVector.add(sectionHeader.getHeadLine());
		}

		final JList sectionList = new JList(sectionVector);
		JScrollPane scrollPane = new JScrollPane(sectionList);
		scrollPane.setBounds(10, 59, 272, 191);
		add(scrollPane);


		Vector<String> topicVector = new Vector<String>();
		for (TopicHeader topicHeader : this.section.getAllTopicHeaders()) {
			topicVector.add(topicHeader.getHeadLine());
		}
		final JList topicList = new JList(topicVector);
		JScrollPane scrollPane_1 = new JScrollPane(topicList);
		scrollPane_1.setBounds(378, 59, 328, 260);
		add(scrollPane_1);

		btnEnterTopic.setFont(new Font("Tahoma", Font.PLAIN, 10));
		btnEnterTopic.setBounds(599, 330, 107, 23);
		btnEnterTopic.setEnabled(false);
		btnEnterTopic.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent arg0) {
				ForumWorker<AInnerPanel> worker = new ForumWorker<AInnerPanel>(outerPanel.getConnection()){
					@Override
					protected AInnerPanel doInBackground() throws Exception {
						int selectedTopic = topicList.getSelectedIndex();
						int askedTopicID = section.getTopicHeader(selectedTopic).getElementID();
						GUIAnswer ans = request(RequestType.GET_TOPIC, new Object[] {askedTopicID});
						outerPanel.setNumOfConnected(ans.getNumOfConnected());
						AInnerPanel returnedPanel = null;
						if(ans.getAnswerType().equals(AnswerType.ANSWER)){
							returnedPanel = new TopicViewPanel((Topic) ans.getArguments()[0],outerPanel);
						}
						else {
							returnedPanel = handleEnterTopicExceptions((Exception) ans.getArguments()[0]);
						}
						return returnedPanel;
					}
					@Override
					public void done(){
						try {
							outerPanel.swapInnerPanel(get());
						} catch (InterruptedException e) {
							outerPanel.swapInnerPanel(handleEnterTopicExceptions(e));
						} catch (ExecutionException e) {
							outerPanel.swapInnerPanel(handleEnterTopicExceptions(e));
						}
					}

					private AInnerPanel handleEnterTopicExceptions(Exception thrown){
						try {
							throw thrown;
						} catch (WrongElementIDException e) {
							JOptionPane.showMessageDialog(null, "the topic you are trying to open was deleted by another user", "Topic deleted",JOptionPane.ERROR_MESSAGE);
							return SectionPanel.this;
						} catch (SystemFailureException e) {
							JOptionPane.showMessageDialog(null, "system is unavalible at the moment, please try again later\n" + e.getMessage(), "Error",JOptionPane.ERROR_MESSAGE);
							return requestHomePanel(outerPanel);
						} catch (Exception e) {
							JOptionPane.showMessageDialog(null, "operation failed! please try again\n" + e.getMessage(), "Error",JOptionPane.ERROR_MESSAGE);
							return requestHomePanel(outerPanel);
						}
					}
				};
				worker.execute();
			}
		});
		add(btnEnterTopic);

		panelHeadline.setFont(new Font("Cooper Black", Font.PLAIN, 18));
		panelHeadline.setHorizontalAlignment(SwingConstants.CENTER);
		panelHeadline.setBounds(255, 11, 205, 33);
		add(panelHeadline);

		sectionList.addListSelectionListener(new ListSelectionListener(){

			@Override
			public void valueChanged(ListSelectionEvent e) {
				btnEnterSection.setEnabled(true);
			}
		});

		btnEnterSection.setFont(new Font("Tahoma", Font.PLAIN, 10));
		btnEnterSection.setBounds(175, 261, 107, 23);
		btnEnterSection.setEnabled(false);
		btnEnterSection.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				ForumWorker<AInnerPanel> worker = new ForumWorker<AInnerPanel>(outerPanel.getConnection()){
					@Override
					protected AInnerPanel doInBackground() throws Exception {
						AInnerPanel returnedPanel = SectionPanel.this;
						int selectedSection = sectionList.getSelectedIndex();
						int askedSectionID = section.getSectionHeader(selectedSection).getElementID();
						GUIAnswer ans = request(RequestType.GET_SETCION, new Object[] {askedSectionID});
						outerPanel.setNumOfConnected(ans.getNumOfConnected());
						if(ans.getAnswerType().equals(AnswerType.ANSWER)){
							returnedPanel = new SectionPanel((Section) ans.getArguments()[0],editAuth,outerPanel);
						}
						else {
							returnedPanel = handleEnterSectionExceptions((Exception) ans.getArguments()[0]);
						}
						return returnedPanel;
					}
					@Override
					public void done(){
						try {
							outerPanel.swapInnerPanel(get());
						} catch (InterruptedException e) {
							outerPanel.swapInnerPanel(handleEnterSectionExceptions(e));
						} catch (ExecutionException e) {
							outerPanel.swapInnerPanel(handleEnterSectionExceptions(e));
						}
					}

					private AInnerPanel handleEnterSectionExceptions(Exception thrown){
						try {
							throw thrown;
						} catch (WrongElementIDException e) {
							JOptionPane.showMessageDialog(null, "the section you are trying to open was deleted by another user", "Topic deleted",JOptionPane.ERROR_MESSAGE);
							return SectionPanel.this;
						} catch (SystemFailureException e) {
							JOptionPane.showMessageDialog(null, "system is unavalible at the moment, please try again later\n" + e.getMessage(), "Error",JOptionPane.ERROR_MESSAGE);
							return requestHomePanel(outerPanel);
						} catch (Exception e) {
							JOptionPane.showMessageDialog(null, "operation failed! please try again\n" + e.getMessage(), "Error",JOptionPane.ERROR_MESSAGE);
							return requestHomePanel(outerPanel);
						}
					}
				};
				worker.execute();
			}
		});
		add(btnEnterSection);

		topicList.addListSelectionListener(new ListSelectionListener(){

			@Override
			public void valueChanged(ListSelectionEvent e) {
				btnEnterTopic.setEnabled(true);
				btnDeleteThisSection.setEnabled(true);
			}
		});

		lblSections.setHorizontalAlignment(SwingConstants.CENTER);
		lblSections.setFont(new Font("Cooper Black", Font.PLAIN, 16));
		lblSections.setBounds(10, 38, 272, 22);
		add(lblSections);

		lblTopics.setHorizontalAlignment(SwingConstants.CENTER);
		lblTopics.setFont(new Font("Cooper Black", Font.PLAIN, 16));
		lblTopics.setBounds(378, 38, 328, 22);
		add(lblTopics);


		if (this.section.getElementID()!=0) {
			btnBack.setFont(new Font("Tahoma", Font.PLAIN, 10));
			btnBack.setBounds(615, 18, 91, 23);
			btnBack.addActionListener(new ActionListener(){

				@Override
				public void actionPerformed(ActionEvent arg0) {
					ForumWorker<AInnerPanel> worker = new ForumWorker<AInnerPanel>(outerPanel.getConnection()){

						@Override
						protected AInnerPanel doInBackground() throws Exception {
							GUIAnswer ans = request(RequestType.GET_SETCION, new Object[] {section.getParentID()});
							outerPanel.setNumOfConnected(ans.getNumOfConnected());
							AInnerPanel returnedPanel = null;
							if(ans.getAnswerType().equals(AnswerType.ANSWER)){
								returnedPanel = new SectionPanel((Section) ans.getArguments()[0],editAuth,outerPanel);
							}
							else {
								handleBackExceptions((Exception) ans.getArguments()[0]);
							}
							return returnedPanel;
						}

						@Override
						public void done(){
							try {
								outerPanel.swapInnerPanel(get());
							} catch (InterruptedException e) {
								outerPanel.swapInnerPanel(handleBackExceptions(e));
							} catch (ExecutionException e) {
								outerPanel.swapInnerPanel(handleBackExceptions(e));
							}
						}

						private AInnerPanel handleBackExceptions(Exception thrown){
							try {
								throw thrown;
							} catch (WrongElementIDException e) {
								JOptionPane.showMessageDialog(null, "the section you are trying to open was deleted by another user", "Section deleted",JOptionPane.ERROR_MESSAGE);
								return requestHomePanel(outerPanel);
							} catch (SystemFailureException e) {
								JOptionPane.showMessageDialog(null, "system is unavalible at the moment, please try again later\n" + e.getMessage(), "Error",JOptionPane.ERROR_MESSAGE);
								return requestHomePanel(outerPanel);
							} catch (Exception e) {
								JOptionPane.showMessageDialog(null, "operation failed! please try again\n" + e.getMessage(), "Error",JOptionPane.ERROR_MESSAGE);
								return requestHomePanel(outerPanel);
							}
						}
					};

					worker.execute();
				}
			});
			add(btnBack);
		}

		btnEditSection.setFont(new Font("Tahoma", Font.PLAIN, 10));
		btnEditSection.setBounds(58, 296, 107, 23);
		btnEditSection.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent arg0) {
				ForumWorker<AInnerPanel> worker = new ForumWorker<AInnerPanel>(outerPanel.getConnection()){

					@SuppressWarnings("unchecked")
					@Override
					protected AInnerPanel doInBackground() throws Exception {
						AInnerPanel returnedPanel = SectionPanel.this;
						GUIAnswer ans = request(RequestType.GET_USER_LIST, new Object[] {});
						outerPanel.setNumOfConnected(ans.getNumOfConnected());
						if(ans.getAnswerType().equals(AnswerType.ANSWER)){
							returnedPanel = new EditSectionDetailsPanel(outerPanel,section, (Vector<String>) ans.getArguments()[0]);
						}
						else {
							handleEditSectionExceptions((Exception) ans.getArguments()[0]);
						}
						return returnedPanel;
					}

					@Override
					public void done(){
						try {
							outerPanel.swapInnerPanel(get());
						} catch (InterruptedException e) {
							outerPanel.swapInnerPanel(handleEditSectionExceptions(e));
						} catch (ExecutionException e) {
							outerPanel.swapInnerPanel(handleEditSectionExceptions(e));
						}
					}

					private AInnerPanel handleEditSectionExceptions(Exception thrown){
						try {
							throw thrown;
						} catch (UnAuthorizedException e) {
							JOptionPane.showMessageDialog(null, "you are not authorized to edit section", "UnAuthorized use",JOptionPane.ERROR_MESSAGE);
							return SectionPanel.this;
						} catch (SystemFailureException e) {
							JOptionPane.showMessageDialog(null, "system is unavalible at the moment, please try again later\n" + e.getMessage(), "Error",JOptionPane.ERROR_MESSAGE);
							return requestHomePanel(outerPanel);
						} catch (Exception e) {
							JOptionPane.showMessageDialog(null, "operation failed! please try again\n" + e.getMessage(), "Error",JOptionPane.ERROR_MESSAGE);
							return requestHomePanel(outerPanel);
						}
					}
				};

				worker.execute();
			}
		});
		if (this.editAuth)
			add(btnEditSection);


		btnAddSection.setFont(new Font("Tahoma", Font.PLAIN, 10));
		btnAddSection.setBounds(175, 295, 107, 23);
		btnAddSection.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent arg0) {
				ForumWorker<AInnerPanel> worker = new ForumWorker<AInnerPanel>(outerPanel.getConnection()){

					@SuppressWarnings("unchecked")
					@Override
					protected AInnerPanel doInBackground() throws Exception {
						AInnerPanel returnedPanel = SectionPanel.this;
						GUIAnswer ans = request(RequestType.GET_USER_LIST, new Object[] {});
						outerPanel.setNumOfConnected(ans.getNumOfConnected());
						if(ans.getAnswerType().equals(AnswerType.ANSWER)){
							returnedPanel = new CreateSectionPanel(outerPanel,(Vector<String>) ans.getArguments()[0],section.getElementID());
						}
						else {
							returnedPanel = handleAddSectionExceptions((Exception) ans.getArguments()[0]);
						}
						return returnedPanel;
					}

					@Override
					public void done(){
						try {
							outerPanel.swapInnerPanel(get());
						} catch (InterruptedException e) {
							outerPanel.swapInnerPanel(handleAddSectionExceptions(e));
						} catch (ExecutionException e) {
							outerPanel.swapInnerPanel(handleAddSectionExceptions(e));
						}
					}

					private AInnerPanel handleAddSectionExceptions(Exception thrown){
						try {
							throw thrown;
						} catch (UnAuthorizedException e) {
							JOptionPane.showMessageDialog(null, "you are not authorized to edit section", "UnAuthorized use",JOptionPane.ERROR_MESSAGE);
							return SectionPanel.this;
						} catch (SystemFailureException e) {
							JOptionPane.showMessageDialog(null, "system is unavalible at the moment, please try again later\n" + e.getMessage(), "Error",JOptionPane.ERROR_MESSAGE);
							return requestHomePanel(outerPanel);
						} catch (Exception e) {
							JOptionPane.showMessageDialog(null, "operation failed! please try again\n" + e.getMessage(), "Error",JOptionPane.ERROR_MESSAGE);
							return requestHomePanel(outerPanel);
						}
					}
				};

				worker.execute();
			}
		});
		if (this.editAuth)
			add(btnAddSection);

		btnDeleteThisSection.setFont(new Font("Tahoma", Font.PLAIN, 10));
		btnDeleteThisSection.setBounds(175, 330, 107, 21);
		btnDeleteThisSection.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent arg0) {
				ForumWorker<AInnerPanel> worker = new ForumWorker<AInnerPanel>(outerPanel.getConnection()){
					@Override
					protected AInnerPanel doInBackground() throws Exception {
						int selectedSection = sectionList.getSelectedIndex();
						int askedSectionID = section.getSectionHeader(selectedSection).getElementID();
						GUIAnswer ans = request(RequestType.REMOVE_SECTION, new Object[] {askedSectionID});
						outerPanel.setNumOfConnected(ans.getNumOfConnected());
						AInnerPanel returnedPanel = null;
						if(ans.getAnswerType().equals(AnswerType.ANSWER)){
							returnedPanel = new SectionPanel((Section) ans.getArguments()[0],editAuth,outerPanel);
						}
						else {
							handleDeleteSectionExceptions((Exception) ans.getArguments()[0]);
						}
						return returnedPanel;
					}
					@Override
					public void done(){
						try {
							outerPanel.swapInnerPanel(get());
						} catch (InterruptedException e) {
							outerPanel.swapInnerPanel(handleDeleteSectionExceptions(e));
						} catch (ExecutionException e) {
							outerPanel.swapInnerPanel(handleDeleteSectionExceptions(e));
						}
					}

					private AInnerPanel handleDeleteSectionExceptions(Exception thrown){
						try {
							throw thrown;
						} catch (WrongElementIDException e) {
							JOptionPane.showMessageDialog(null, "the section you are trying to change was deleted by another user", "Topic deleted",JOptionPane.ERROR_MESSAGE);
							return requestHomePanel(outerPanel);
						} catch (UnAuthorizedException e) {
							JOptionPane.showMessageDialog(null, "you are not authorized to delete this section", "UnAuthorized use",JOptionPane.ERROR_MESSAGE);
							return SectionPanel.this;
						} catch (SystemFailureException e) {
							JOptionPane.showMessageDialog(null, "system is unavalible at the moment, please try again later\n" + e.getMessage(), "Error",JOptionPane.ERROR_MESSAGE);
							return requestHomePanel(outerPanel);
						} catch (Exception e) {
							JOptionPane.showMessageDialog(null, "operation failed! please try again\n" + e.getMessage(), "Error",JOptionPane.ERROR_MESSAGE);
							return requestHomePanel(outerPanel);
						}
					}
				};
				worker.execute();
			}
		});
		if (this.editAuth)
			add(btnDeleteThisSection);

		btnAddNewTopic.setFont(new Font("Tahoma", Font.PLAIN, 10));
		btnAddNewTopic.setBounds(378, 330, 107, 23);
		btnAddNewTopic.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent arg0) {
				ForumWorker<AInnerPanel> worker = new ForumWorker<AInnerPanel>(outerPanel.getConnection()){
					@Override
					protected AInnerPanel doInBackground() throws Exception {
						return new EditorPanel(outerPanel,section);
					}
					@Override
					public void done(){
						try {
							outerPanel.swapInnerPanel(get());
						} catch (InterruptedException e) {
							JOptionPane.showMessageDialog(null, "operation failed! please try again\n" + e.getMessage(), "Error",JOptionPane.ERROR_MESSAGE);
						} catch (ExecutionException e) {
							JOptionPane.showMessageDialog(null, "operation failed! please try again\n" + e.getMessage(), "Error",JOptionPane.ERROR_MESSAGE);
						}
					}
				};
				worker.execute();
			}
		});
		if (outerPanel.getCurrentSet() != SetType.GUEST)
			add(btnAddNewTopic);
	}
}
